package cn.bistu.cs.haroldweather.viewpager;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import cn.bistu.cs.haroldweather.MainActivity;
import cn.bistu.cs.haroldweather.R;
import cn.bistu.cs.haroldweather.db.Focuses;

public class Fragment1 extends Fragment {
    private List<String> dataList = new ArrayList<String>();
    private ListView listView;
    private ArrayAdapter<String> adapter;
    private List<Focuses> focusesList = new ArrayList<Focuses>();
    private Focuses selectFocues;
    private Button refresh_button;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_1, container, false);
        listView = view.findViewById(R.id.list_view2);
        refresh_button = view.findViewById(R.id.refresh_button);
        adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList);
        listView.setAdapter(adapter);
        refresh_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPause();
                onResume();
            }
        });
        return view;
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }
    public void onResume() {
        super.onResume();
        Log.e("碎片onResume","开始展示");
        showFocuses();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectFocues = focusesList.get(position);
                Log.e("selectFocues:",selectFocues.toString());
                Log.e("position:",""+position);
                MainActivity activity = (MainActivity) getActivity();
                activity.getWeather(selectFocues.getAdcode(),0);
                activity.checkFocues();
                activity.drawerLayout.closeDrawers();

            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e("fragement2","停止");
    }

    public void showFocuses(){
        dataList.clear();
        focusesList = LitePal.findAll(Focuses.class);
        if(focusesList.size()>0){
            for (int i=0;i<focusesList.size();i++){
                dataList.add(focusesList.get(i).toString());
            }
        }
        adapter.notifyDataSetChanged();
        listView.setSelection(0);
    }
}